import { G } from "./utils/Gloabl";
import Map from "./Map";
import { Rect } from "./libs/Rect";
import { Collisione2dUtil } from "./libs/Collision2dUtil";

const { ccclass } = cc._decorator;

@ccclass
export default class Hero extends cc.Component {

    public anim: cc.Animation;

    public speed: number = 250;

    public spDir: cc.Vec3;
    
    public map: Map;

    private _animState: string;
    public set animState(v: string) {
        if (this._animState == v)
            return;
        this._animState = v;
        this.anim.play(this._animState);
    }

    onLoad() {
        this.anim = this.node.getComponent(cc.Animation);
        this.spDir = new cc.Vec3(0, 0, 0);
        this.map = cc.find("Canvas/bg/map").getComponent(Map);
    }

    update(dt: number) {
        if (G.Input[cc.macro.KEY.a] || G.Input[cc.macro.KEY.left]) {
            this.spDir.x = -1;
        } else if (G.Input[cc.macro.KEY.d] || G.Input[cc.macro.KEY.right]) {
            this.spDir.x = 1;
        } else {
            this.spDir.x = 0;
        }

        if (G.Input[cc.macro.KEY.w] || G.Input[cc.macro.KEY.up]) {
            this.spDir.y = 1;
        }
        else if (G.Input[cc.macro.KEY.s] || G.Input[cc.macro.KEY.down]) {
            this.spDir.y = -1;
        } else {
            this.spDir.y = 0;
        }

        let tempPos = new cc.Vec3();

        cc.Vec3.add(tempPos, this.node.position, this.spDir);
        cc.Vec3.lerp(tempPos, this.node.position, tempPos, dt * this.speed);

        let worldPos = this.node.parent.convertToWorldSpaceAR(tempPos);

        if (!this.map.checkCollision(worldPos)) {
            this.node.setPosition(tempPos);
        }

        let state = "";
        if (this.spDir.x == 1) {
            state = "hero_right";
        } else if (this.spDir.x == -1) {
            state = "hero_left";
        } else if (this.spDir.y == 1) {
            state = "hero_up";
        } else if (this.spDir.y == -1) {
            state = "hero_down";
        }

        if (state) {
            this.animState = state;
        }
    }

    onDestroy(): void {

    }

}
